package ch.bfh.abch.rems.sender.tinkerforge;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import ch.bfh.abch.rems.REMSMulticastController;
import ch.bfh.abch.rems.sender.MulticastSender;
import ch.bfh.abcm.rems.sensors.tinkerforge.TFSensorType;

import com.google.gson.Gson;

public class TFMulticastSender extends MulticastSender {

    private static Logger logger = Logger.getLogger("play");

    protected DatagramSocket socket;
    private InetAddress multicastAdress;
    private int port;

    public TFMulticastSender(String multicastAdress, int port) {
        this.port = port;
        try {
            this.multicastAdress = InetAddress.getByName(multicastAdress);
        } catch (UnknownHostException e) {
            logger.error("UnknownHostException: " + e.getMessage());
        } catch (IOException e) {
            logger.error("IOException: " + e.getMessage());
        }
    }

    public void sendCLusterNodeAverage(int value, String clusterNodeID, TFSensorType sensorType) {
        try {
            socket = new DatagramSocket((port+1));
            byte[] buffer = new byte[REMSMulticastController.DEFAULT_BYTE_ARRAY_LENGTH];
            buffer = getByteArrayFromTFCNA(value, clusterNodeID, sensorType);
            logger.debug("Buffersize: "+buffer.length);
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAdress, port);
            logger.debug("Send CNA as a Multicast{"+multicastAdress+"} on port:{"+port+"}");
            logger.debug("DatagrammPacket"+packet);
            logger.debug("DatagramSocket"+socket);
            socket.send(packet);
            logger.debug("Multicasted...");
        }catch (IOException e){
            logger.error("Exception: "+e.getMessage());
            
        }
        socket.close();
    }
    
    private byte[] getByteArrayFromTFCNA(int value, String clusterNodeID, TFSensorType sensorType){
        logger.info("Create clusterNodeAverageObject as String with Gson");
        TFClusterNodeAverage clusterNodeAverage = new TFClusterNodeAverage(value, clusterNodeID, sensorType);
        String cnaString = new Gson().toJson(clusterNodeAverage);
        logger.debug("SendData: "+cnaString);
        return cnaString.getBytes();
    }
}
